package com.yuandengta.yomall.cart.interceptor;

import com.yuandengta.common.constant.AuthConstant;
import com.yuandengta.common.constant.CartConstant;
import com.yuandengta.common.vo.MemberVO;
import com.yuandengta.yomall.cart.vo.UserVO;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器 {@link CartInterceptor}
 *  - 在执行目标方法之前，判断用户的登录状态，并封装传递给 Controller 目标请求
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserVO> threadLocal = new ThreadLocal<>();

    /**
     * 浏览器有一个cookie：user-key 标识用户身份，一般设置是一个月后过期
     * 如果第一次使用购物车功能，都会给一个临时的用户身份，以后每次访问都会带上这个cookie
     *
     * 登录：session有
     * 未登录：按照cookie里面带来的user-key
     * 第一次：如果没有临时用户，需要创建一个临时用户，并让浏览器保存
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserVO user = new UserVO();
        HttpSession session = request.getSession();
        MemberVO member = (MemberVO)session.getAttribute(AuthConstant.SESSION_LOGIN_USER);
        if (member != null) {
            // 用户登录
            user.setUserId(member.getId());
        }

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                // user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    user.setUserKey(cookie.getValue());
                    user.setTempUser(true);
                }
            }
        }

        // 如果没有临时用户，则创建一个临时用户
        if (StringUtils.isEmpty(user.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            user.setUserKey(uuid);
        }

        threadLocal.set(user);

        return true;
    }

    /**
     * Handler方法处理完成后，创建临时用户，让浏览器保存
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        UserVO user = threadLocal.get();
        if (!user.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, user.getUserKey());
            cookie.setDomain("yomall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
